package v1

import (
	"net/http"
	"strconv"

	"gitee.com/daonna/collab-manage-system/service"

	"github.com/gin-gonic/gin"
)

// SendMessage 发送消息
func SendMessage(c *gin.Context) {
	// 获取当前用户ID（发送者）
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析请求体
	var req struct {
		ConversationID int64  `json:"conversation_id" binding:"required"`
		Content        string `json:"content" binding:"required"`
		ContentType    string `json:"content_type" binding:"omitempty,oneof=text image file audio video location system"`
		FileURL        string `json:"file_url" binding:"omitempty"`
		FileName       string `json:"file_name" binding:"omitempty"`
		FileSize       int64  `json:"file_size" binding:"omitempty"`
		ReplyToID      int64  `json:"reply_to_id" binding:"omitempty"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 默认文本类型
	if req.ContentType == "" {
		req.ContentType = "text"
	}

	// 调用服务层发送消息
	messageID, err := service.SendMessage(
		c.Request.Context(),
		req.ConversationID,
		currentUserID.(uint),
		req.Content,
		req.ContentType,
		req.FileURL,
		req.FileName,
		req.FileSize,
		req.ReplyToID,
	)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "发送消息失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "发送消息成功",
		"data": gin.H{
			"message_id": messageID,
		},
	})
}

// ListMessages 获取会话中的消息
func ListMessages(c *gin.Context) {
	// 获取会话ID
	conversationID, err := strconv.ParseInt(c.Param("conversationId"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的会话ID",
		})
		return
	}

	// 获取当前用户ID
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 获取分页参数
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
	offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
	if limit > 100 {
		limit = 100 // 限制最大查询数量
	}

	// 调用服务层获取消息列表
	messages, err := service.ListMessages(
		c.Request.Context(),
		conversationID,
		currentUserID.(uint),
		limit,
		offset,
	)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取消息失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取消息成功",
		"data":    messages,
	})
}

// UpdateMessage 更新消息（编辑）
func UpdateMessage(c *gin.Context) {
	// 获取消息ID
	messageID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的消息ID",
		})
		return
	}

	// 获取当前用户ID
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析请求体
	var req struct {
		Content string `json:"content" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 调用服务层更新消息
	err = service.UpdateMessage(
		c.Request.Context(),
		messageID,
		currentUserID.(uint),
		req.Content,
	)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "更新消息失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "更新消息成功",
	})
}

// DeleteMessage 删除消息
func DeleteMessage(c *gin.Context) {
	// 获取消息ID
	messageID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的消息ID",
		})
		return
	}

	// 获取当前用户ID
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 调用服务层删除消息
	err = service.DeleteMessage(
		c.Request.Context(),
		messageID,
		currentUserID.(uint),
	)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "删除消息失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "删除消息成功",
	})
} 